<template>
  <div>
    <AcceptHandleHeadComponent
      ref="acceptHandleHeadRef"
      :ucolumns="ucolumns"
      :needMoreQuery="true"
      :type="LableTitle.compreQuery"
      @myEvent="myEvent"
      @setColumns="setColumns"
      @onSearch="search"
      @onReset="reQuery"
    >
      <div slot="headRight" style="margin-right: 20px">
        <a-button type="primary" class="btn_normal_color" style="margin-left: 8px" @click="downloadAllCaseInfo"
          >导出案件情况登记表</a-button
        >
      </div>

      <!-- 其他查询条件 -->
      <div class="accept_main_content_operate_left_icon icon_box" slot="headOperation">
        <div
          @click="changeMain(true)"
          :style="isMain ? 'background-color: #ccc;' : ''"
          class="accept_main_content_operate_left_icon_table algin_justity_center icon_switch"
        >
          主案件
        </div>
        <div
          @click="changeMain(false)"
          class="accept_main_content_operate_left_icon_table algin_justity_center icon_switch"
          :style="!isMain ? 'background-color: #ccc;' : ''"
        >
          子流程
        </div>
      </div>
      <!-- 其他查询条件 -->
      <div slot="more">
        <a-form layout="inline" class="accept_more_operate_moreForm">
          <a-collapse v-model="collapseKey" class="accept_more_operate_moreForm_collapse" style="font-weight: bold">
            <a-collapse-panel :show-arrow="false" disabled  key="1">
              <div slot="header" class="accept_more_operate_moreForm_collapse_head">
                <a-row :gutter="48" style="width: 100%">
                  <a-col @click.stop="() => {}" :md="8" :sm="24">
                    <a-form-item label="案号：">
                      <a-input v-model="queryParam.f_code" placeholder="请输入案号" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col @click.stop="() => {}" :md="8" :sm="24">
                    <a-form-item label="申请人：">
                      <a-input v-model="queryParam.f_applyname" placeholder="请输入申请人" allowClear />
                    </a-form-item>
                  </a-col>
                  <a-col @click.stop="() => {}" :md="8" :sm="24">
                    <a-form-item label="被申请人：">
                      <a-input v-model="queryParam.f_targetname" placeholder="请输入被申请人" allowClear />
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>
              <a-row
                :gutter="48"
                style="width: 100%; margin-left: 0"
                class="accept_more_operate_moreForm_collapse_body"
              >
                <a-form-item label="业务状态：">
                  <a-select
                    v-model="queryParam.f_status"
                    placeholder="请选择申请来源"
                    allowClear
                    style="width: 220px; font-weight: normal"
                  >
                    <a-select-option v-for="status in St_admreviewList" :key="status.value" :value="status.value">
                      {{ status.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </a-form>
      </div>

      <template slot="content">
        <div class="accept_content_table">
          <!-- 表格数据 -->
          <a-table
            :scroll="scroll"
            :columns="ucolumns"
            :data-source="listData"
            :pagination="upagination"
            :loading="loading"
            rowKey="applyid"
            @change="tableChange"
            size="middle"
            :bordered="ubordered"
            :rowClassName="rowClassName"
            :components="header"
            ref="table"
            :key="tableCountKey"
          >
            <span slot="serial" slot-scope="text, record, index">
              {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
            </span>
            <div slot="casestatusSlot" slot-scope="casestatus" class="beyond_hiding" style="width: 100%">
              {{ casestatus in St_admreviewKey ? St_admreviewKey[casestatus].name : '' }}
            </div>
            <!-- 申请人 -->
            <div
              slot="applynameSlot"
              slot-scope="applyname"
              class="beyond_hiding"
              style="width: 100%; text-align: left"
            >
              <a-tooltip placement="topLeft">
                <template slot="title">
                  <span>{{ applyname }}</span>
                </template>
                {{ applyname }}
              </a-tooltip>
            </div>
            <!-- 被申请人 -->
            <div
              slot="targetnameSlot"
              slot-scope="targetname"
              class="beyond_hiding"
              style="width: 100%; text-align: left"
            >
              <a-tooltip placement="topLeft">
                <template slot="title">
                  <span>{{ targetname }}</span>
                </template>
                {{ targetname }}
              </a-tooltip>
            </div>

            <!-- 业务状态 -->
            <div slot="processSlot" slot-scope="process" class="beyond_hiding" style="width: 100%; text-align: left">
              {{ process ? process : '行政复议' }}
            </div>

            <!-- 当前用户 -->
            <template slot="currentuser" slot-scope="text, record">
              <div v-if="text || record.currentuser" style="width: 100%; text-align: left">
                {{ text ? text : record.currentuser }}
              </div>

              <a-tooltip v-else-if="record.currentgroup" placement="topLeft">
                <!-- <template slot="title">
                  {{ record.groupname }}
                </template> -->
                <div style="width: 100%; text-align: left">{{ record.groupname }}</div>
              </a-tooltip>
              <span v-else> </span>
            </template>
            <!-- 状态 -->
            <template slot="status" slot-scope="text" v-if="text != ''">
              <a-tag :color="text == 1 ? 'blue' : 'orange'">
                {{ text == 1 ? '在办' : '挂起' }}
              </a-tag>
            </template>

            <!-- 	案件来源 -->
            <div slot="sourceSlot" slot-scope="source" class="beyond_hiding" style="width: 100%">
              {{ source in Tp_applysourceMap ? Tp_applysourceMap[source] : '' }}
            </div>

            <!-- 	案件状态 -->
            <div slot="decisiontypeSlot" slot-scope="decisiontype" class="beyond_hiding" style="width: 100%">
              {{ decisiontype in Tp_decision ? Tp_decision[decisiontype].name : '' }}
            </div>

            <!-- 	结案类型 -->
            <div slot="statusSlot" slot-scope="status" class="beyond_hiding" style="width: 100%">
              {{ status in St_apply ? St_apply[status].name : '' }}
            </div>

            <!-- 	程序类型 -->
            <div slot="proctypeSlot" slot-scope="proctype" class="beyond_hiding" style="width: 100%">
              {{ proctype in Tp_apptype ? Tp_apptype[proctype].name : '' }}
            </div>

            <!-- 受理人 -->
            <div
              slot="dealNameSlot"
              slot-scope="text, record"
              class="beyond_hiding"
              style="width: 100%; text-align: left"
            >
              <a-tooltip placement="topLeft">
                <template slot="title">
                  <span>{{ dealNameLabel(record) }}</span>
                </template>
                {{ dealNameLabel(record) }}
              </a-tooltip>
            </div>

            <div slot="subtimeSlot" slot-scope="subtime" class="beyond_hiding" style="width: 100%">
              {{ subtime | getTimeFormat('YYYY年M月D日') }}
            </div>

            <span slot="operation" slot-scope="text, record">
              <template>
                <a href="javascript:;" @click="caseView(record)">详情</a>
                <span v-if="isMain">
                  <a-divider type="vertical" />
                  <a href="javascript:;" @click="caseRecord(record)">记录</a>
                </span>
              </template>
            </span>
          </a-table>
        </div>
      </template>
    </AcceptHandleHeadComponent>
    <!-- 案件记录 -->
    <a-drawer
      title="案件记录"
      width="40%"
      placement="right"
      :closable="false"
      :visible="visible"
      @close="
        () => {
          visible = false
        }
      "
    >
      <ProcessRecords ref="processRecordsRef" />
    </a-drawer>
  </div>
</template>

<script>
import { AcceptCompreQuery, AcceptSubCompreQuery } from '@/api/workflow/wf_CompreQuery.js'
import { getViewTaskByInstid } from '@/api/worktasks/wt_personal.js'
import { Tp_applysourceMap } from '@/enumeration/Tp_applysource.js'
import { Tp_decision } from '@/enumeration/Tp_decision.js'
import { St_apply } from '@/enumeration/St_apply.js'
import { Tp_apptype } from '@/enumeration/Tp_apptype.js'
import { St_admreviewKey, St_admreviewList } from '@/enumeration/St_admreview'
import drag from '@/components/TableDrag/drag'
import { LableTitle } from '@/enumeration/LableTitle'
import { exportAllCase } from '@/api/apply/apl_main.js'
import { downloadFile } from '@/utils/util'

const ucolumns = [
  {
    title: '序号',
    width: 50,
    align: 'center',
    fixed: 'left',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '业务状态',
    width: 180,
    align: 'center',
    dataIndex: 'process',
    scopedSlots: { customRender: 'processSlot' }
  },
  {
    title: '环节',
    width: 100,
    align: 'center',
    dataIndex: 'casestatus',
    scopedSlots: { customRender: 'casestatusSlot' }
  },
  {
    title: '案件编号',
    width: 230,
    dataIndex: 'acceptcode',
    align: 'center'
  },
  {
    title: '申请人',
    width: 100,
    dataIndex: 'applyname',
    align: 'center',
    scopedSlots: { customRender: 'applynameSlot' }
  },
  {
    title: '被申请人',
    width: 230,
    dataIndex: 'targetname',
    align: 'center',
    scopedSlots: { customRender: 'targetnameSlot' }
  },
  {
    title: '承办人',
    width: 120,
    key: 'dealName',
    dataIndex: 'dealName',
    align: 'center',
    scopedSlots: { customRender: 'dealNameSlot' }
  },
  // {
  //   title: '当前环节',
  //   dataIndex: 'steps',
  //   width: '100px',
  //   align: 'center',
  // },
  {
    title: '当前处理人',
    dataIndex: 'currentuser',
    width: 120,
    align: 'center',
    scopedSlots: { customRender: 'currentuser' }
  },
  {
    title: '结案类型',
    width: 100,
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'statusSlot' }
  },
  {
    title: '案件状态',
    width: 150,
    dataIndex: 'decisiontype',
    align: 'center',
    scopedSlots: { customRender: 'decisiontypeSlot' }
  },
  {
    title: '程序类型',
    width: 120,
    dataIndex: 'proctype',
    align: 'center',
    scopedSlots: { customRender: 'proctypeSlot' }
  },
  {
    title: '案件来源',
    width: 120,
    dataIndex: 'source',
    align: 'center',
    scopedSlots: { customRender: 'sourceSlot' }
  },
  {
    title: '申请日期',
    width: 140,
    dataIndex: 'subtime',
    align: 'center',
    scopedSlots: { customRender: 'subtimeSlot' }
  },
  {
    title: '操作',
    width: 100,
    dataIndex: 'action',
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  data () {
    return {
      visible: false, // 抽屉状态
      Tp_applysourceMap: Tp_applysourceMap,
      Tp_decision: Tp_decision,
      St_apply: St_apply,
      Tp_apptype: Tp_apptype,
      St_admreviewList: St_admreviewList,
      St_admreviewKey: St_admreviewKey,
      collapseKey: [1], // 折叠面板key
      queryParam: {
        f_applyname: undefined, // 申请人
        f_targetname: undefined, // 被申请人
        f_code: undefined, // 案号
        f_status: undefined, // 行政复议状态
        pageNumber: 1,
        pageSize: 20
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      ucolumns: ucolumns,
      mixins: [drag],
      header: undefined,
      tableCountKey: 0,
      LableTitle: LableTitle,
      isMain: false,
      scroll: { x: 1000, y: 410 }
    }
  },
  created () {
    console.log('this.$route.query.queryParam.queryList', this.$route.query.queryParam)
    let routeParam
    try {
      routeParam = JSON.parse(JSON.stringify(this.$route.query.queryParam))
      this.queryParam = { ...this.queryParam, ...this.$route.query.queryParam }
    } catch {
      console.log('路由传参非json格式')
    }
    this.queryList()
  },
  watch: {
    ucolumns: {
      handler (newValue, oldVal) {
        this.headerChange()
      },
      deep: true // 深度监听
    }
  },
  methods: {
    myEvent (e) {
      if (e) {
        this.scroll.y = this.scroll.y + e
      } else {
        this.scroll.y = 410
      }
    },
    // 案件记录
    caseRecord (record) {
      console.log('案件记录', record.processinstanceid)
      this.visible = true
      this.$nextTick(() => {
        this.$refs.processRecordsRef.f_init(record.processinstanceid)
      })
    },
    headerChange () {
      console.log('移动后', this.ucolumns)
      this.header = {
        header: {
          cell: drag.methods.initDrag(this.ucolumns)
        }
      }
    },
    setColumns (columns) {
      console.log('重置前', this.ucolumns)
      // tableCountKey自增是为了让表格控件每次销毁强制更新
      this.tableCountKey += 1
      this.ucolumns = columns
      // this.ucolumns = columns
      console.log('重置后', this.ucolumns)
    },
    // 搜索
    search (val) {
      if (val) {
        this.queryParam.f_code = val
      }
      this.queryParam.pageNumber = 1
      this.queryList()
    },
    // 查看操作
    async caseView (record) {
      const { data } = await getViewTaskByInstid(record.processinstanceid)
      if (data == null) {
        this.$message.error('未找到taskid')
        return
      }
      this.$router.push({
        path: `/CompreQueryHandleOperation/${data}/4`,
        query: {
          url: '/AcceptCompreQuery',
          queryParam: this.queryParam
        }
      })
    },
    // 父子流程切换
    changeMain (val) {
      if (val == this.isMain) {
        return
      }
      this.isMain = val
      this.reQuery()
    },
    // 查询列表数据
    async queryList () {
      const queryParam = this.getCpQueryParam()
      this.loading = true
      let res
      if (this.isMain) {
        res = await AcceptCompreQuery(queryParam).finally(() => {
          this.loading = false
        })
      } else {
        res = await AcceptSubCompreQuery(queryParam).finally(() => {
          this.loading = false
        })
      }
      // const { data } = await AcceptCompreQuery(queryParam).finally(() => {
      //   this.loading = false
      // })
      this.listData = res.data.records || []
      this.upagination.total = res.data.total
      this.upagination.current = res.data.current
      this.upagination.pageSize = res.data.size
    },
    // 接收时间监听判断开始结束日期是否合理
    subtimeListen () {
      if (
        this.queryParam.f_startdate > this.queryParam.f_startdate_01 &&
        this.queryParam.f_startdate &&
        this.queryParam.f_startdate_01
      ) {
        this.queryParam.f_startdate = undefined
      }
      if (
        this.queryParam.f_enddate > this.queryParam.f_enddate_01 &&
        this.queryParam.f_enddate &&
        this.queryParam.f_enddate_01
      ) {
        this.queryParam.f_enddate = undefined
      }
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      this.queryParam = {
        f_applyname: undefined, // 申请人
        f_targetname: undefined, // 被申请人
        f_code: undefined, // 案号
        f_status: undefined, // 行政复议状态
        pageNumber: 1,
        pageSize: 20
      }
      this.queryList()
    },
    // 复制查询对象
    getCpQueryParam () {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.f_startdate?.format) {
        cpQueryParam.f_startdate = this.queryParam.f_startdate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_startdate_01?.format) {
        cpQueryParam.f_startdate_01 = this.queryParam.f_startdate_01.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_enddate?.format) {
        cpQueryParam.f_enddate = this.queryParam.f_enddate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_enddate_01?.format) {
        cpQueryParam.f_enddate_01 = this.queryParam.f_enddate_01.format('YYYY-MM-DD') + ' 00:00:00'
      }
      return cpQueryParam
    },
    // 重置表头方法
    resetting () {
      this.$refs.headerDefRef.f_resetting()
    },
    // 子组件回调函数, 重置表头
    s_setColumns (columns) {
      this.ucolumns = columns
    },
    // 显示自定义表头组件
    showHeaderDef (e) {
      this.$refs.headerDefRef.f_init(e)
    },
    // 表格翻页
    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },
    /**
     * 案件承办人
     * @param {} record
     */
    dealNameLabel (record) {
      let dealName = record.hearfirstname || record.acceptfirstname
      if (dealName && (record.hearsecondname || record.acceptsecondname)) {
        dealName = dealName + '，' + (record.hearsecondname || record.acceptsecondname)
      }
      return dealName
    },
    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },

    /**
     *	导出全部案件的信息表
     */
    downloadAllCaseInfo () {
      exportAllCase()
        .then(response => {
          downloadFile(response, '案件情况登记表.xlsx')
        })
        .catch(function () {
          console.log(error)
        })
    }
  },
  components: {
    AcceptHandleHeadComponent: () => import('@/views/accept/component/AcceptHandleHeadComponent.vue'),
    ProcessRecords: () => import('@/views/base/ProcessRecords.vue')
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';

.formArea {
  margin-bottom: 30px;
}

.headerdefBox img {
  height: 20px;
  width: 20px;
}
.headerdefBox {
  // border: 1px solid red;
  margin: 0 10px 10px 0;
  display: flex;
  justify-content: end;
}

.collapseArea {
  border: none;
  .ant-collapse-item {
    border-bottom: none;
  }
  /deep/.ant-collapse-content {
    border-top: none;
  }
}
/deep/ .ant-collapse-header {
  background-color: #fff;
}
.collapseArea_header {
  .ant-form-item {
    margin-bottom: 0;
  }
}

.collapseArea_body {
  padding-top: 10px;
  padding: 0 20px 0 0px;
}

.icon_box {
  // border: 1px solid red;
  width: 150px;
  min-width: 150px;
  margin-right: 8px;
}
.icon_switch {
  cursor: pointer;
  font-weight: 550;
  width: 50%;
}
::v-deep .ant-card-head {
  border-bottom: 1px solid red !important;
}
</style>
